package com.droidexchange.main;

import java.util.ArrayList;
import java.util.List;
import net.sf.stackwrap4j.entities.Comment;
import net.sf.stackwrap4j.entities.MajorPost;
import android.content.Context;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import com.droidexchange.R;
import com.droidexchange.custom.AnswerTabPanel;
import com.droidexchange.util.StringFormatter;
import com.droidexchange.util.Util;
import com.droidexchange.util.StringFormatter.StringElem;

public class DeMajorPost implements OnClickListener
{
	public MajorPost			majorPost;
	private StringFormatter		strFormatter		= new StringFormatter();
	private ArrayList<View>		displayLayout		= new ArrayList<View>();
	LinearLayout				commentsView;
	private boolean				hasComments			= false;
	private int					answerTabVisibility	= View.VISIBLE;
	private static Context		context;
	private static final String	SHOW_COMMENTS		= "Show Comments";
	private static final String	HIDE_COMMENTS		= "Hide Comments";

	public static void setContext(Context ctxt)
	{
		context = ctxt;
	}

	public DeMajorPost(MajorPost majorPost)
	{
		this.majorPost = majorPost;
		try
		{
			displayLayout.clear();
			createDisplayText();
			setCommentsText();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void attachDisplayText(View mainView)
	{
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		layoutParams.setMargins(10, 10, 0, 0);

		LinearLayout ansContainer = (LinearLayout) mainView.findViewById(R.id.answer_container);
		ansContainer.removeAllViews();
		for (int i = 0; i < displayLayout.size(); i++)
		{
			View view = displayLayout.get(i);
			removeParentFromView(view);
			//view.setVisibility(View.VISIBLE);
			ansContainer.addView(view, layoutParams);
		}

		setVisibility(getAnswersVisiblity(), ansContainer);

		// if (hasComments())
		// {
		// LinearLayout commentsHolder = (LinearLayout)
		// mainView.findViewById(R.id.comments_holder);
		// removeParentFromView(commentsView);
		// commentsHolder.addView(commentsView, layoutParams);
		// }
		
		dumpData("attachDisplayText", ansContainer);
	}

	@Override
	public void onClick(View view)
	{
		if (view instanceof Button)
		{
			Button btnComments = (Button) view;
			LinearLayout llGrandParent = (LinearLayout) view.getParent().getParent();
			TextView txtComments = (TextView) llGrandParent.findViewById(R.id.txt_comments);
			if (btnComments.getText().equals(SHOW_COMMENTS))
			{
				btnComments.setText(HIDE_COMMENTS);
				txtComments.setVisibility(View.VISIBLE);
			}
			else
			{
				btnComments.setText(SHOW_COMMENTS);
				txtComments.setVisibility(View.GONE);
			}
		}
		else if (view instanceof AnswerTabPanel)
		{
			LinearLayout llParent = (LinearLayout) view.getParent();
			LinearLayout ansContainer = (LinearLayout) llParent.findViewById(R.id.answer_container);
			if (getAnswersVisiblity() == View.VISIBLE)
			{
				answerTabVisibility = View.GONE;
				setVisibility(View.GONE, ansContainer);
			}
			else
			{
				answerTabVisibility = View.VISIBLE;
				setVisibility(View.VISIBLE, ansContainer);
			}
			
			dumpData("onclick", ansContainer);
		}
	}

	public boolean hasComments()
	{
		return hasComments;
	}

	public int getAnswersVisiblity()
	{
		return answerTabVisibility;
	}

	public void setAnswersVisiblity(int bVisible)
	{
		answerTabVisibility = bVisible;
	}

	private void setCommentsText() throws Exception
	{
		List<Comment> comments = majorPost.getComments();
		SpannableStringBuilder ssbCommentsText = new SpannableStringBuilder();
		hasComments = (comments.size() > 0);
		if (!hasComments)
			return;

		for (int i = 0; i < comments.size(); i++)
		{
			Comment comment = comments.get(i);
			int score = comment.getScore();
			if (score > 0)
				ssbCommentsText = ssbCommentsText.append(Html.fromHtml("<font color=\"#0000FF\"><b> " + score
						+ "</b></font>  "));

			ssbCommentsText = ssbCommentsText.append(Html.fromHtml(comment.getBody() + " - <font color=\"#0000FF\">"
					+ comment.getOwner().getDisplayName() + "</font>"));
			ssbCommentsText = ssbCommentsText.append("\n\n");
		}

		commentsView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.comments_block, null);
		Button btnComments = (Button) commentsView.findViewById(R.id.btn_comments);
		btnComments.setText(SHOW_COMMENTS);
		btnComments.setTag(majorPost.getPostId());
		btnComments.setOnClickListener(this);

		TextView txtComments = (TextView) commentsView.findViewById(R.id.txt_comments);
		txtComments.setText(ssbCommentsText, BufferType.SPANNABLE);
	}

	private void removeParentFromView(View view)
	{
		if (view == null)
			return;

		LinearLayout parent = (LinearLayout) view.getParent();
		if (parent != null)
			parent.removeView(view);
	}

	private void createDisplayText()
	{
		try
		{
			ArrayList<StringElem> elems = strFormatter.format(majorPost.getBody());
			for (int i = 0; i < elems.size(); i++)
			{
				StringElem elem = elems.get(i);
				if (elem.type == StringFormatter.TYPE_HTML)
				{
					Spanned ssb = Html.fromHtml(elem.cs.toString());
					TextView txtView = getViewForNormalText();
					txtView.setText(ssb, BufferType.SPANNABLE);
					displayLayout.add(txtView);
				}
				else if (elem.type == StringFormatter.TYPE_CODE)
				{
					View hsv = getViewForCodeText(elem.cs);
					displayLayout.add(hsv);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private TextView getViewForNormalText()
	{
		TextView txtView = new TextView(context);
		txtView.setTextColor(context.getResources().getColor(R.color.text_normal));
		txtView.setSingleLine(false);
		return txtView;
	}

	private View getViewForCodeText(CharSequence cs)
	{
		TextView txtView = new TextView(context);
		txtView.setTextColor(context.getResources().getColor(R.color.text_normal));
		txtView.setBackgroundColor(context.getResources().getColor(R.color.text_bg_code));
		txtView.setSingleLine(false);
		txtView.setTextSize(10);

		String code = cs.toString().replace("&lt;", "<").replace("&gt;", ">");
		Spanned ssb = new SpannableStringBuilder(code);
		txtView.setText(ssb, BufferType.SPANNABLE);

		HorizontalScrollView hsv = new HorizontalScrollView(context);
		hsv.addView(txtView);

		return hsv;
	}

	@SuppressWarnings("unused")
	private SpannableStringBuilder getText()
	{
		SpannableStringBuilder csAll = new SpannableStringBuilder();
		try
		{
			ArrayList<StringElem> elems = strFormatter.format(majorPost.getBody());
			for (int i = 0; i < elems.size(); i++)
			{
				StringElem elem = elems.get(i);
				if (elem.type == StringFormatter.TYPE_HTML)
				{
					csAll = csAll.append(Html.fromHtml(elem.cs.toString()));
				}
				else if (elem.type == StringFormatter.TYPE_CODE)
				{
					SpannableStringBuilder ssb = new SpannableStringBuilder(elem.cs);
					ssb.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, elem.cs.length(), 0);
					csAll = csAll.append(ssb);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return csAll;
	}

	private void dumpData(String s, View view)
	{
		Util.log(s + " Data dump for post #" + majorPost.getPostId());
		Util.log("answerTabVisibility = " + (answerTabVisibility == View.VISIBLE ? "VISIBLE" : "GONE"));
		Util.log(view + " Visibility = " + (view.getVisibility() == View.VISIBLE ? "VISIBLE" : "GONE"));
		Util.log("=========================\n");
	}
	
	private void setVisibility(int v, View view)
	{
		view.setVisibility(v);
	}
}
